import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { Save, Plus, Trash2, Edit, AlertTriangle, CheckCircle, Hand } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, Button, Input, Switch, FormControlLabel, Select, MenuItem } from '@mui/material';
import logger from '../../../utils/logger';

// 样式组件
const Container = styled.div`
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
`;

const ContentWrapper = styled.div`
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
`;

const PageHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
`;

const PageTitle = styled.h1`
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const ActionButton = styled.button`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background-color: #40a9ff;
    transform: translateY(-1px);
  }

  &:active {
    transform: translateY(0);
  }

  &:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
    transform: none;
  }
`;

const Section = styled.div`
  margin-bottom: 32px;
`;

const SectionTitle = styled.h2`
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e0e0e0;
`;

const ConfigTable = styled.div`
  display: grid;
  gap: 16px;
  margin-bottom: 24px;
`;

const ConfigItem = styled.div`
  display: grid;
  grid-template-columns: 200px 1fr 100px;
  gap: 16px;
  align-items: center;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  background-color: ${props => props.isActive ? '#f6ffed' : 'white'};
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
`;

const ConfigLabel = styled.div`
  font-weight: 500;
  color: #333;
`;

const ConfigValue = styled.div`
  color: #666;
`;

const ConfigActions = styled.div`
  display: flex;
  gap: 8px;
  justify-content: flex-end;
`;

const IconButton = styled.button`
  padding: 6px;
  background-color: transparent;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &:hover {
    background-color: #f0f0f0;
  }

  svg {
    width: 16px;
    height: 16px;
  }
`;

const SaveMessage = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  margin-bottom: 24px;
  color: #389e0d;
`;

const PalmAnalysisConfig = () => {
  // 状态管理
  const [loading, setLoading] = useState(true);
  const [configData, setConfigData] = useState({
    palmLines: [],
    interpretations: [],
    globalSettings: {
      isEnabled: true,
      defaultConfidenceThreshold: 0.75,
      analyzeBothHands: true
    }
  });
  const [openEditDialog, setOpenEditDialog] = useState(false);
  const [currentEditItem, setCurrentEditItem] = useState(null);
  const [editType, setEditType] = useState(null);
  const [editForm, setEditForm] = useState({});
  const [saveSuccess, setSaveSuccess] = useState(false);

  // 模拟获取配置数据
  useEffect(() => {
    // 记录页面访问日志
    logger.info('进入手相分析配置管理页面');
    
    const fetchConfigData = async () => {
      try {
        setLoading(true);
        // 在实际应用中，这里应该调用API获取数据
        // const response = await axios.get('/api/admin/palm-analysis/config');
        // 模拟数据
        setTimeout(() => {
          const mockData = {
            palmLines: [
              { id: '1', name: '生命线', description: '代表健康和生命力', isActive: true },
              { id: '2', name: '智慧线', description: '代表智力和思维方式', isActive: true },
              { id: '3', name: '感情线', description: '代表感情和人际关系', isActive: true },
              { id: '4', name: '事业线', description: '代表职业和事业发展', isActive: true },
              { id: '5', name: '财运线', description: '代表财富和财运', isActive: true }
            ],
            interpretations: [
              { id: '1', lineId: '1', condition: '深长清晰', interpretation: '生命力旺盛，健康长寿', confidenceLevel: 0.9 },
              { id: '2', lineId: '1', condition: '短浅模糊', interpretation: '体质较弱，需注意健康', confidenceLevel: 0.85 },
              { id: '3', lineId: '2', condition: '直长', interpretation: '思维理性，逻辑清晰', confidenceLevel: 0.8 },
              { id: '4', lineId: '2', condition: '弯曲', interpretation: '思维灵活，富有创造力', confidenceLevel: 0.85 },
              { id: '5', lineId: '3', condition: '平滑', interpretation: '感情稳定，人际关系和谐', confidenceLevel: 0.8 },
              { id: '6', lineId: '4', condition: '明显', interpretation: '事业运势强，职业发展顺利', confidenceLevel: 0.9 }
            ],
            globalSettings: {
              isEnabled: true,
              defaultConfidenceThreshold: 0.75,
              analyzeBothHands: true
            }
          };
          setConfigData(mockData);
          setLoading(false);
        }, 500);
      } catch (error) {
        console.error('获取手相分析配置失败:', error);
        setLoading(false);
      }
    };

    fetchConfigData();
  }, []);

  // 处理编辑掌纹
  const handleEditPalmLine = (palmLine) => {
    setCurrentEditItem(palmLine);
    setEditType('palmLine');
    setEditForm({ ...palmLine });
    setOpenEditDialog(true);
  };

  // 处理编辑解读
  const handleEditInterpretation = (interpretation) => {
    setCurrentEditItem(interpretation);
    setEditType('interpretation');
    setEditForm({ ...interpretation });
    setOpenEditDialog(true);
  };

  // 处理添加新掌纹
  const handleAddPalmLine = () => {
    setCurrentEditItem(null);
    setEditType('palmLine');
    setEditForm({ name: '', description: '', isActive: true });
    setOpenEditDialog(true);
  };

  // 处理添加新解读
  const handleAddInterpretation = () => {
    setCurrentEditItem(null);
    setEditType('interpretation');
    setEditForm({ 
      lineId: configData.palmLines[0]?.id || '', 
      condition: '', 
      interpretation: '', 
      confidenceLevel: 0.8 
    });
    setOpenEditDialog(true);
  };

  // 处理删除掌纹
  const handleDeletePalmLine = (id) => {
    if (window.confirm('确定要删除这个掌纹类型吗？这将同时删除相关的所有解读。')) {
      // 记录删除掌纹类型日志
      logger.info(`删除手相分析掌纹类型，ID: ${id}`);
      
      setConfigData(prev => ({
        ...prev,
        palmLines: prev.palmLines.filter(pl => pl.id !== id),
        interpretations: prev.interpretations.filter(i => i.lineId !== id)
      }));
    }
  };

  // 处理删除解读
  const handleDeleteInterpretation = (id) => {
    if (window.confirm('确定要删除这个解读吗？')) {
      // 记录删除解读日志
      logger.info(`删除手相分析解读，ID: ${id}`);
      
      setConfigData(prev => ({
        ...prev,
        interpretations: prev.interpretations.filter(i => i.id !== id)
      }));
    }
  };

  // 处理表单输入变化
  const handleFormChange = (field, value) => {
    setEditForm(prev => ({ ...prev, [field]: value }));
  };

  // 处理保存编辑
  const handleSaveEdit = () => {
    if (editType === 'palmLine') {
      if (currentEditItem) {
        // 更新现有掌纹
        // 记录编辑掌纹日志
        logger.info('编辑手相分析掌纹类型', { id: currentEditItem.id, name: editForm.name });
        
        setConfigData(prev => ({
          ...prev,
          palmLines: prev.palmLines.map(pl => 
            pl.id === currentEditItem.id ? { ...editForm, id: pl.id } : pl
          )
        }));
      } else {
        // 添加新掌纹
        // 记录添加掌纹日志
        logger.info('添加手相分析掌纹类型', { name: editForm.name });
        
        const newPalmLine = {
          ...editForm,
          id: Date.now().toString()
        };
        setConfigData(prev => ({
          ...prev,
          palmLines: [...prev.palmLines, newPalmLine]
        }));
      }
    } else if (editType === 'interpretation') {
      if (currentEditItem) {
        // 更新现有解读
        // 记录编辑解读日志
        logger.info('编辑手相分析解读', { id: currentEditItem.id, lineId: editForm.lineId, condition: editForm.condition });
        
        setConfigData(prev => ({
          ...prev,
          interpretations: prev.interpretations.map(i => 
            i.id === currentEditItem.id ? { ...editForm, id: i.id } : i
          )
        }));
      } else {
        // 添加新解读
        // 记录添加解读日志
        logger.info('添加手相分析解读', { lineId: editForm.lineId, condition: editForm.condition });
        
        const newInterpretation = {
          ...editForm,
          id: Date.now().toString()
        };
        setConfigData(prev => ({
          ...prev,
          interpretations: [...prev.interpretations, newInterpretation]
        }));
      }
    }
    setOpenEditDialog(false);
  };

  // 处理保存所有配置
  const handleSaveAllConfig = async () => {
    try {
      // 记录保存配置日志
      logger.info('保存手相分析所有配置');
      
      // 在实际应用中，这里应该调用API保存数据
      // await axios.post('/api/admin/palm-analysis/config', configData);
      // 模拟保存
      setTimeout(() => {
        setSaveSuccess(true);
        setTimeout(() => setSaveSuccess(false), 3000);
      }, 500);
    } catch (error) {
      console.error('保存配置失败:', error);
      // 记录保存错误日志
      logger.error('保存手相分析配置失败', error);
    }
  };

  // 处理全局设置变更
  const handleGlobalSettingChange = (field, value) => {
    setConfigData(prev => ({
      ...prev,
      globalSettings: {
        ...prev.globalSettings,
        [field]: value
      }
    }));
  };

  if (loading) {
    return (
      <Container>
        <ContentWrapper>
          <div style={{ display: 'flex', justifyContent: 'center', padding: '48px' }}>
            <div>加载中...</div>
          </div>
        </ContentWrapper>
      </Container>
    );
  }

  return (
    <Container>
      <ContentWrapper>
        <PageHeader>
          <PageTitle>
            <Hand size={24} />
            手相分析配置管理
          </PageTitle>
          <ActionButton onClick={handleSaveAllConfig}>
            <Save size={16} />
            保存所有配置
          </ActionButton>
        </PageHeader>

        {saveSuccess && (
          <SaveMessage>
            <CheckCircle size={20} />
            配置保存成功！
          </SaveMessage>
        )}

        {/* 全局设置 */}
        <Section>
          <SectionTitle>全局设置</SectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16, color: '#334155' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={configData.globalSettings.isEnabled}
                    onChange={(e) => handleGlobalSettingChange('isEnabled', e.target.checked)}
                    color="primary"
                  />
                }
                label="启用手相分析功能"
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <span style={{ minWidth: 150 }}>默认置信度阈值:</span>
              <Input
                type="number"
                min="0"
                max="1"
                step="0.01"
                value={configData.globalSettings.defaultConfidenceThreshold}
                onChange={(e) => handleGlobalSettingChange('defaultConfidenceThreshold', parseFloat(e.target.value))}
                style={{ width: 100 }}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={configData.globalSettings.analyzeBothHands}
                    onChange={(e) => handleGlobalSettingChange('analyzeBothHands', e.target.checked)}
                  />
                }
                label="分析双手"
              />
            </div>
          </div>
        </Section>

        {/* 掌纹类型管理 */}
        <Section>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <SectionTitle>掌纹类型管理</SectionTitle>
            <ActionButton onClick={handleAddPalmLine} style={{ backgroundColor: '#52c41a' }}>
              <Plus size={16} />
              添加掌纹类型
            </ActionButton>
          </div>
          <ConfigTable>
            {configData.palmLines.map(palmLine => (
              <ConfigItem key={palmLine.id} isActive={palmLine.isActive}>
                <ConfigLabel>{palmLine.name}</ConfigLabel>
                <ConfigValue>
                  <div>{palmLine.description}</div>
                  <div style={{ color: '#999', fontSize: '12px', marginTop: 4 }}>
                    状态: {palmLine.isActive ? '启用' : '禁用'}
                  </div>
                </ConfigValue>
                <ConfigActions>
                  <IconButton onClick={() => handleEditPalmLine(palmLine)} title="编辑">
                    <Edit size={16} color="#1890ff" />
                  </IconButton>
                  <IconButton onClick={() => handleDeletePalmLine(palmLine.id)} title="删除">
                    <Trash2 size={16} color="#ff4d4f" />
                  </IconButton>
                </ConfigActions>
              </ConfigItem>
            ))}
          </ConfigTable>
        </Section>

        {/* 解读管理 */}
        <Section>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <SectionTitle>掌纹解读管理</SectionTitle>
            <ActionButton onClick={handleAddInterpretation} style={{ backgroundColor: '#52c41a' }}>
              <Plus size={16} />
              添加解读
            </ActionButton>
          </div>
          <ConfigTable>
            {configData.interpretations.map(interpretation => {
              const palmLine = configData.palmLines.find(pl => pl.id === interpretation.lineId);
              return (
                <ConfigItem key={interpretation.id}>
                  <ConfigLabel>
                    {palmLine?.name || '未知掌纹'} - {interpretation.condition}
                  </ConfigLabel>
                  <ConfigValue>
                    <div>{interpretation.interpretation}</div>
                    <div style={{ color: '#999', fontSize: '12px', marginTop: 4 }}>
                      置信度: {(interpretation.confidenceLevel * 100).toFixed(0)}%
                    </div>
                  </ConfigValue>
                  <ConfigActions>
                    <IconButton onClick={() => handleEditInterpretation(interpretation)} title="编辑">
                      <Edit size={16} color="#1890ff" />
                    </IconButton>
                    <IconButton onClick={() => handleDeleteInterpretation(interpretation.id)} title="删除">
                      <Trash2 size={16} color="#ff4d4f" />
                    </IconButton>
                  </ConfigActions>
                </ConfigItem>
              );
            })}
          </ConfigTable>
        </Section>

        {/* 编辑对话框 */}
        <Dialog open={openEditDialog} onClose={() => setOpenEditDialog(false)}>
          <DialogTitle>
          {editType === 'palmLine' ? 
            (currentEditItem ? '编辑掌纹类型' : '添加掌纹类型') : 
            (currentEditItem ? '编辑掌纹解读' : '添加掌纹解读')
          }
        </DialogTitle>
          <DialogContent>
            {editType === 'palmLine' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>掌纹名称</label>
                  <Input
                    fullWidth
                    value={editForm.name}
                    onChange={(e) => handleFormChange('name', e.target.value)}
                    placeholder="请输入掌纹名称"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>掌纹描述</label>
                  <Input
                    fullWidth
                    value={editForm.description}
                    onChange={(e) => handleFormChange('description', e.target.value)}
                    placeholder="请输入掌纹描述"
                  />
                </div>
                <FormControlLabel
                  control={
                    <Switch
                      checked={editForm.isActive}
                      onChange={(e) => handleFormChange('isActive', e.target.checked)}
                    />
                  }
                  label="启用此掌纹类型"
                />
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>所属掌纹</label>
                  <Select
                    fullWidth
                    value={editForm.lineId}
                    onChange={(e) => handleFormChange('lineId', e.target.value)}
                  >
                    {configData.palmLines.map(pl => (
                      <MenuItem key={pl.id} value={pl.id}>{pl.name}</MenuItem>
                    ))}
                  </Select>
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>纹路特征</label>
                  <Input
                    fullWidth
                    value={editForm.condition}
                    onChange={(e) => handleFormChange('condition', e.target.value)}
                    placeholder="如：深长清晰、短浅模糊、弯曲等"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>解读内容</label>
                  <Input
                    fullWidth
                    value={editForm.interpretation}
                    onChange={(e) => handleFormChange('interpretation', e.target.value)}
                    placeholder="请输入解读内容"
                  />
                </div>
                <div>
                  <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>置信度</label>
                  <Input
                    fullWidth
                    type="number"
                    min="0"
                    max="1"
                    step="0.01"
                    value={editForm.confidenceLevel}
                    onChange={(e) => handleFormChange('confidenceLevel', parseFloat(e.target.value))}
                  />
                </div>
              </div>
            )}
          </DialogContent>
          <div style={{ padding: '16px', display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <Button onClick={() => setOpenEditDialog(false)}>取消</Button>
            <Button onClick={handleSaveEdit} color="primary">保存</Button>
          </div>
        </Dialog>
      </ContentWrapper>
    </Container>
  );
};

export default PalmAnalysisConfig;